﻿using System;
using System.Collections.Generic;
using System.IO;
using CsvHelper;
using System.Globalization;
using CsvHelper.Configuration;

namespace ARgoCsv
{
    // 定义一个泛型类 ARgoCsv，用于处理 CSV 文件的读取和写入
    public class ARgoCsv<T>
    {
        private readonly string csvFilePath; // CSV 文件路径
        private readonly char delimiter; // CSV 文件的分隔符
        private readonly CsvConfiguration config; // CSV 配置

        // 构造函数，初始化 CSV 文件路径，允许设置分隔符
        public ARgoCsv(string path, char delimiter = '\t')
        {
            csvFilePath = path ?? throw new ArgumentNullException(nameof(path), "CSV file path cannot be null.");
            this.delimiter = delimiter;
            this.config = new CsvConfiguration(CultureInfo.InvariantCulture)
            {
                Delimiter = delimiter.ToString(),
            };
        }

        // 读取数据
        public List<T> Load()
        {
            if (!File.Exists(csvFilePath))
            {
                return new List<T>(); // 如果文件不存在，返回空列表
            }

            using (var fileStream = new FileStream(csvFilePath, FileMode.Open, FileAccess.Read))
            using (var reader = new StreamReader(fileStream))
            using (var csv = new CsvReader(reader, config))
            {
                return new List<T>(csv.GetRecords<T>());
            }

        }

        // 清空数据
        public void Clear()
        {
            Save(new List<T>()); // 保存空列表
        }

        // 保存数据
        public void Save(List<T> items)
        {
            using (var writer = new StreamWriter(csvFilePath))
            using (var csv = new CsvWriter(writer, config))
            {
                csv.WriteRecords(items); // 一次性写入所有记录
            }
        }
    }
}
